<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
    <script src="js/jquery-3.7.1.js"></script>
</head>
<body>
    <h1>用户登录</h1>
    <form id="loginForm">
        用户名：<input type="text" name="username"><br>
        密码：<input type="password" name="password"><br>
        <button type="submit" id="btnlogin">登录</button>
    </form>
    <script>
        $("#loginForm").on("submit", function (event) {
            event.preventDefault();
            // 获取用户名和密码
            var name = $("input[name='username']").val();
            var pwd = $("input[name='password']").val();
            if (name === "" || pwd === "") {
                alert("用户名或密码不能为空");
                return false;
            }
            // 发送请求
            $.ajax({
                url: "login",
                type: 'post',
                data: {
                    username: name,
                    password: pwd
                },
                success: function (data) {
                    if(data === "success") {
                        // 保存用户名
                        localStorage.setItem("user", name);
                        // 跳转到index.html页面
                        window.location.href = "index.html";
                    }else {
                        alert("用户名或密码错误");
                        // 清空表单
                        $("input[name='username']").val('');
                        $("input[name='password']").val('');
                    }

                }, complete: function () {
                    // 无论成功或失败，重新启用按钮
                    $("#btnlogin").prop("disabled", false);
                }
            });
        });
    </script>
</body>
</html>
